const Koa = require('koa');
const faker = require('faker');

const app = new Koa();

const createRandomList = (count) => {
    return new Array(count).fill(1).map((_, idx) => ({
        id: Date.now() + idx,
        name: faker.lorem.sentences(),
    }));
};

app.use(async (context, next) => {
    context.set({
        'Access-Control-Allow-Origin': 'http://localhost:3002',
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Method': 'POST,GET,PUT,DELETE',
    });
    await next();
});

app.use(async (ctx) => {
    const { method, path, query } = ctx;
    if (method.toLocaleLowerCase() === 'get' && path === '/list') {
        const { count } = query;
        const data = createRandomList(Number(count) || 30);
        ctx.status = 200;
        ctx.body = JSON.stringify(data);
    }
});

app.listen(8008, () => {
    console.log('Server is running~');
});
